package cn.itsource.interceptor;

import cn.hutool.json.JSONUtil;
import cn.itsource.util.JsonResult;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static cn.itsource.util.PetHomeConstant.SYSTEM_LOGIN_ERROR;
import static cn.itsource.util.RedisContants.LOGIN_USER_KEY;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-17 14:52:00
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取到请求头的token
        String token = request.getHeader("token");

        //判断token是否为空
        if (!loginTimeOut(token,request,response)){
            return false;
        }
        //拼接key
        String key = LOGIN_USER_KEY + token;
        //查询redis中的token是否存在
        String empToken = stringRedisTemplate.opsForValue().get(key);
        //若redis中不存在
        if (!loginTimeOut(empToken,request,response)){
            return false;
        }

        //redis中存在，再次刷新时间,放行
        stringRedisTemplate.opsForValue().set(key,empToken);
        return true;
    }


    public static boolean loginTimeOut(String value,HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (Strings.isBlank(value)){
            //返回错误信息
            response.setContentType("application/json;charset=UTF-8");
            JsonResult result = JsonResult.error("登入信息过期", SYSTEM_LOGIN_ERROR);
            String jsonResult = JSONUtil.toJsonStr(result);
            PrintWriter writer = response.getWriter();
            writer.write(jsonResult);
            return false;
        }
        return true;
    }
}
